package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.mapper.ChargingPileMapper;
import com.woniuxy.model.dto.StartChargingDto;
import com.woniuxy.model.entity.ChargingPile;
import com.woniuxy.model.entity.ChargingRecords;
import com.woniuxy.service.ChargingRecordsService;
import com.woniuxy.mapper.ChargingRecordsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
* @author Administrator
* @description 针对表【charging_records】的数据库操作Service实现
* @createDate 2025-01-02 20:02:38
*/
@Service
public class ChargingRecordsServiceImpl extends ServiceImpl<ChargingRecordsMapper, ChargingRecords>
    implements ChargingRecordsService{

    @Autowired
    private ChargingPileMapper chargingPileMapper;

    @Autowired
    private ChargingRecordsMapper chargingRecordsMapper;

    // 生成充电订单号
    @Override
    public String generateOrderNumber() {
        return "CD" + System.currentTimeMillis() + (int)(Math.random() * 1000);
    }

    @Override
    public String startCharging(StartChargingDto chargingDto) {
        // 生成唯一订单号
        String orderNumber = generateOrderNumber();

        // 构建充电记录
        ChargingRecords record = new ChargingRecords();
        record.setOrderNumber(orderNumber);
        record.setCustomerId(chargingDto.getCustomerId());
        record.setPileId(chargingDto.getPileId());
        record.setStationId(chargingDto.getStationId());
        record.setAmount(BigDecimal.ZERO); // 初始金额为 0
        record.setElectricityQuantity(BigDecimal.ZERO); // 初始电量为 0
        record.setStatus("进行中"); // 设置状态
        record.setCreateTime(new Date());

        // 插入数据库
        chargingRecordsMapper.insert(record);

        // 更新充电桩状态为“使用中”
        ChargingPile chargingPile = chargingPileMapper.selectById(chargingDto.getPileId());
        if (chargingPile != null) {
            chargingPile.setPileStatus("使用中");
            chargingPileMapper.updateById(chargingPile);
        } else {
            throw new RuntimeException("充电桩不存在");
        }

        return orderNumber;
    }

    @Override
    public boolean applyRefund(String orderNumber, BigDecimal refundAmount, String refundDescription) {
        // 设置退款状态为申请中或已退款（视情况而定）
        int refundStatus = 1; // 1 表示申请中或已退款（可以根据业务需求设置不同的状态）
        Date refundTime = new Date(); // 当前时间作为退款时间

        // 更新退款状态
        int result = chargingRecordsMapper.updateRefundStatus(orderNumber, refundStatus, refundAmount, refundTime, refundDescription);
        return result > 0;
    }


}




